package com.tinyideatech.system.aspect;

import com.tinyideatech.common.utils.IpUtils;
import com.tinyideatech.system.entity.SysLog;
import com.tinyideatech.system.service.ISysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;


@Aspect
@Component
@SuppressWarnings("all")
public class SystemLogAspect {

    @Autowired
    private ISysLogService sysLogService;

    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

    @Pointcut("@annotation(com.tinyideatech.system.aspect.SysLogServiceAspect)")
    public void serviceAspect() {

    }

    @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        String ip = IpUtils.getIpAddr(request);
        String params = "";
        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                params.concat(joinPoint.getArgs()[i].toString() + ";");
            }
        }
        try {
            SysLog sysLog = new SysLog();
            sysLog.setAction(getServiceMethodDescription(joinPoint));
            sysLog.setIp(ip);
            sysLog.setCreateBy("admin");
            sysLogService.save(sysLog);
        } catch (Exception ex) {
            logger.error("================ error log =================");
            logger.error("err message:{}", ex.getMessage());
        }
    }

    public static String getServiceMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] classes = method.getParameterTypes();
                if (classes.length == arguments.length) {
                    description = method.getAnnotation(SysLogServiceAspect.class).description();
                    break;
                }
            }
        }
        return description;
    }
}
